import React from 'react';
import { Redirect, Link, withRouter, SessionModelState } from 'umi';
import { connect } from 'react-redux';

import styles from './index.less';
import { LOGINED_USER_SESSION } from '@/configs/constants';
import Store from '@/utils/store';
import { LoadPanel, Popup } from 'devextreme-react';
import { getUrlByName } from '@/utils/configsReader';

const portal_system_url = getUrlByName('portal_system_url');

interface IProps {
  session: SessionModelState;
  loading: boolean;
  dispatch: any;
  history: any; // TODO:确定类型.
  location: any;
}
class LoginView extends React.Component<IProps, any> {
  constructor(props: IProps) {
    super(props);
  }

  componentDidMount() {
    let token = this.props.location.query.token as string;
    if (token) {
      token = token.replace('Bearer ', '');
      Store.set(LOGINED_USER_SESSION, { token });
      this.getUserProfile(token);
    }
  }

  render() {
    const {
      loading,
      session: { userSession },
    } = this.props;

    if (userSession?.profile) {
      // 进入首页
      return <Redirect to="/" />;
    }

    return (
      <>
        <LoadPanel
          message={'用户身份验证中...'}
          visible={loading}
          // position={{ of: '#tips' }}
        />
        {!loading && (
          <div id="tips" className={styles['not_login_tips']}>
            <h2>会话过期或尚未登录,请先登录...</h2>
            <br />
            <a href={portal_system_url}>统一登录系统Portal</a>
          </div>
          //   <Popup
          //   width={'334'}
          //   height={'auto'}
          //   closeOnOutsideClick={false}
          //   title={"统一登录"}
          //   showTitle={false}
          //   visible={loading === false}
          //   onHiding={() => null}
          //   className="photo-popup-content">
          //   <iframe
          //     title="统一登录"
          //     src={`${portal_system_url}/login`}
          //     className={styles['portal_iframe']}
          //   // scrolling="auto"
          //   />
          // </Popup>
          // http://118.31.184.21:6543/login
        )}
      </>
    );
  }

  /**
   * 用户已在Portal门户网站登录,现在带着token过来.需要获取用户权限.
   */
  getUserProfile = (token: string) => {
    this.props.dispatch({ type: 'session/getUserProfile', payload: { token } });
  };

  redirectToPortal = () => {
    this.props.history.push(portal_system_url);
  };
}

const mapStateToProps = (state: any) => {
  const session: SessionModelState = state.session;
  return {
    session,
    loading: state.loading.global && state.loading.models.session, // dvaJs自带的loading(每个model共用一个)
  };
};

const mapDispatchToProps = (dispatch: any) => {
  return {
    dispatch,
  };
};

export default withRouter(
  connect(mapStateToProps, mapDispatchToProps)(LoginView),
);
